package encode

import (
	"crypto/md5"
	"encoding/base64"
	"fmt"
	"io"

	jsoniter "github.com/json-iterator/go"
)

func MD5(content string) string {
	w := md5.New()
	io.WriteString(w, content)
	bytes := w.Sum(nil)
	return fmt.Sprintf("%x", bytes)
}

func Base64StdEncode(src string) string {
	return base64.StdEncoding.EncodeToString([]byte(src))
}

func Base64StdDecode(src string) (string, error) {
	bytes, err := base64.StdEncoding.DecodeString(src)
	if err != nil {
		return "", err
	}
	return string(bytes), nil
}

func Base64URLEncode(src string) string {
	return base64.URLEncoding.EncodeToString([]byte(src))
}

func Base64URLDecode(src string) (string, error) {
	bytes, err := base64.URLEncoding.DecodeString(src)
	if err != nil {
		return "", err
	}
	return string(bytes), nil
}

func HashCode(src interface{}, md5 bool) string {
	dest := fmt.Sprint(src)
	if md5 {
		return MD5(dest)
	}
	return dest
}

var json = jsoniter.Config{
	EscapeHTML:             true,
	SortMapKeys:            true,
	ValidateJsonRawMessage: true,
	UseNumber:              true,
}.Froze()

func Marshal(v interface{}) ([]byte, error) {
	return json.Marshal(v)
}

func UnMarshal(data []byte, v interface{}) error {
	return json.Unmarshal(data, v)
}
